<template>
  <div class="table-wrapper">
    <div>
      <el-button type="primary" @click="summarizeData">汇总教练成交学员信息</el-button>
    </div>
    <div>
      <p>共
        <el-tag>{{ tableData.length }}</el-tag>
        条体验课成交数据
      </p>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column prop="orgCode" label="机构编号"/>
      <el-table-column prop="orgName" label="机构名称"/>
      <el-table-column prop="deliveryOrg" label="交付机构"/>
      <el-table-column prop="userAccount" label="用户账号"/>
      <el-table-column prop="userName" label="用户姓名"/>
      <el-table-column prop="coachAccount" label="陪练账号"/>
      <el-table-column prop="coachName" label="陪练姓名"/>
      <el-table-column prop="materialName" label="资料名称"/>
      <el-table-column prop="materialType" label="资料类型"/>
      <el-table-column prop="coachType" label="陪练类型"/>
      <el-table-column prop="reviewMethod" label="复习方式"/>
      <el-table-column prop="deleteStatus" label="删除状态"/>
      <el-table-column prop="practiceTime" label="练习时间"/>
    </el-table>

    <result-dialog
      :visible.sync="dialogVisible"
      :result="summaryResult"
    />
  </div>
</template>

<script>
import ResultDialog from '@/views/systemTools/systemSalarySettlement/step/step3/ResultDialog.vue'

export default {
  name: 'deletePracticeRecords',
  components: { ResultDialog },
  props: {
    tableData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      summaryResult: []
    }
  },
  methods: {
    summarizeData() {
      const resultMap = {}

      // 遍历 tableData
      this.tableData.forEach(item => {
        if (!resultMap[item.coachAccount]) {
          resultMap[item.coachAccount] = {
            coachName: item.coachName,
            userNames: []
          }
        }
        resultMap[item.coachAccount].userNames.push(item.userName)
      })

      // 输出结果
      const result = Object.keys(resultMap).map(key => {
        return {
          coachAccount: key,
          coachName: resultMap[key].coachName,
          userNames: resultMap[key].userNames.join(' ')
        }
      })

      this.summaryResult = result
      this.dialogVisible = true
      // 自动复制到剪贴板
      navigator.clipboard.writeText(JSON.stringify(result, null, 2))
        .then(() => {
          this.$message.success('已复制到剪贴板！')
        })
        .catch(err => {
          console.error('复制失败', err)
          this.$message.error('复制失败，请检查浏览器权限。')
        })
      return result
    }
  }
}
</script>

<style scoped lang="scss">
.table-wrapper {
  padding: 20px;
}
</style>
